package com.itheima.tlias84.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias84.service.impl.LoginServiceImpl;
import com.itheima.tlias84.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import com.itheima.tlias84.entity.Log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Aspect 标识切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Resource
    HttpServletRequest request;
    @Resource
    LoginServiceImpl loginService;

    @Around("@annotation(com.itheima.tlias84.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint point){
        Log list = new Log();
        String token = request.getHeader("token");

            //可以使用建造者模式简化
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            String username = jsonObject.getString("username");
            list.setOperateEmpName(username);
            log.info("操作人是{}", username);
            Object[] args = point.getArgs();
            list.setMethodParams(Arrays.toString(args));
            log.info("请求参数是{}", args);
            Object target1 = point.getTarget();
            String name = target1.getClass().getName();
            list.setClassName(name);
            log.info("获取类名target{}", target1);


        LocalDateTime now = LocalDateTime.now();


        list.setOperateTime(now);
        long start = System.currentTimeMillis();
        //执行父类方法
        try {
            Object proceed = point.proceed();
            list.setReturnValue(proceed.toString());
            log.info("获取返回值proceed{}", proceed);
            long end = System.currentTimeMillis() - start;
            list.setCostTime((int) end);
            list.setMethodName(point.getSignature().getName());
            log.info("{}接口执行时间为{}", point.getSignature().getName(), end);
            loginService.insertLog(list);
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
